package com.example.sxmall.service.action.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.sxmall.auth.Authentication;
import com.example.sxmall.auth.UserInfo;
import com.example.sxmall.controller.shopCart.vo.ProductVO;
import com.example.sxmall.controller.shopCart.vo.ShopCartVO;
import com.example.sxmall.controller.shopCart.vo.StoreProductVO;
import com.example.sxmall.redis.ShopCartKey;
import com.example.sxmall.service.ShopCartService;
import com.example.sxmall.service.action.ActionCartService;
import com.example.sxmall.service.dto.OperateCartDTO;
import com.example.sxmall.service.dto.ShopCartDTO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Description: TODO
 * @Author whh-yt
 * @Date 2022/3/17 4:31 下午
 */
@Service
public class UpdateCartActionService extends ActionCartService {

    @Override
    public ShopCartVO execute(OperateCartDTO operateCartDTO) {
        Long storeId = operateCartDTO.getStoreId();
        ProductVO productVO = operateCartDTO.getProduct();
        UserInfo userInfo = Authentication.getUserInfo();
        ShopCartDTO shopCartCache = redisService.get(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId(), ShopCartDTO.class);
        if (Objects.isNull(shopCartCache) || CollectionUtils.isEmpty(shopCartCache.getStoreProductList())) {
            return new ShopCartVO();
        }
        String version = shopCartCache.getVersion();
        List<StoreProductVO> storeProductList = shopCartCache.getStoreProductList();
        // 需要更新的商品
        // TODO 目前只有一家店铺
        StoreProductVO storeProductVO = storeProductList.get(0);
        List<ProductVO> productListCache = storeProductVO.getProductList();
        for (ProductVO item : productListCache) {
            String skuCode = item.getSkuCode();
            if (productVO.getSkuCode().equals(skuCode)) {
                item.setBuyCount(productVO.getBuyCount() > item.getMaxPurchase() ? item.getMaxPurchase() : productVO.getBuyCount());
            }
        }
        ShopCartDTO shopCartDTO = new ShopCartDTO();
        shopCartDTO.setVersion(ShopCartService.SHOPCART_VERSION);
        shopCartDTO.setStoreProductList(storeProductList);
        // 需要更新的商品
        redisService.set(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId(), shopCartDTO);
        return super.execute(operateCartDTO);
    }
}
